<template>
  <div class="app-container">
    <!--第1部分：搜索-->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        :placeholder="$t('user.userName')"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t("table.search") }}
      </el-button>

      <el-button
        icon="reset"
        type="primary"
        class="filter-item"
        style="margin-left: 10px"
        @click="resetName"
      >重置</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t("table.add") }}
      </el-button>
    </div>

    <!--第2部分：表格-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        :label="$t('table.id')"
        prop="id"
        align="center"
        width="80"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.date')" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.creationTime | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('user.userName')"
        width="150px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('user.fullName')"
        width="150px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.fullName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('user.role')" width="150px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.roles.map((x) => x.name).join("，") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.status')"
        class-name="status-col"
        width="100"
      >
        <template slot-scope="{ row }">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="creator"
        label="创建者"
        width="110px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.creator ? row.creator.userName : "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t("table.edit") }}
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ $t("table.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--第3部分： 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <!--第4部分：添加/编辑对话框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('user.userName')" prop="userName">
          <el-input
            v-model="temp.userName"
            type="text"
            placeholder="请输入"
            :readonly="temp.id > 0"
          />
        </el-form-item>
        <el-form-item :label="$t('user.fullName')" prop="fullName">
          <el-input v-model="temp.fullName" type="text" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          v-if="temp.id > 0"
          :label="$t('user.role')"
          prop="roleNames"
        >
          <el-select
            v-model="temp.roleNames"
            multiple
            placeholder="选择角色"
            size="large"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('login.password')" prop="password">
          <el-input
            v-model="temp.password"
            type="password"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="surePassword">
          <el-input
            v-model="temp.surePassword"
            type="password"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item :label="$t('table.status')" prop="status">
          <el-radio-group v-model="temp.status" size="large">
            <el-radio-button label="正常" />
            <el-radio-button label="禁用" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 在js脚本开头引入组件，包含：用户管理API、获取全部角色API、波纹效果、时间格式化、翻页组件。
import { getUserList, addUser, updateUser, deleteUser } from '@/api/user'
import { getAllRoleList } from '@/api/role'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: 'User',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusMap = {
        0: '禁用',
        1: '正常'
      }
      return statusMap[status]
    }
  },
  /**
   * 初始化组件数据
   * 包括表格数据、分页信息、表单数据、验证规则等
   */
  data() {
    return {
      // 用于重新渲染表格的键值，当数据结构变化时更新此值
      tableKey: 0,
      // 用户列表数据
      list: null,
      // 列表总数
      total: 0,
      creator: '', // 创建者
      remark: '', // 备注
      surePassword: '',
      // 数据加载状态
      listLoading: true,
      // 列表查询参数
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        importance: undefined, // 重要性筛选条件
        title: undefined, // 标题筛选条件
        type: undefined // 类型筛选条件
      },
      // 临时对象，用于存储表单数据
      temp: {
        id: undefined,
        userName: '',
        fullName: '',
        remark: '',
        status: '正常'
      },
      // 表单对话框显示状态
      dialogFormVisible: false,
      // 表单对话框操作状态：'create'或'update'
      dialogStatus: '',
      // 操作文本映射
      textMap: {
        update: '编辑',
        create: '创建'
      },
      // 表单验证规则
      rules: {
        userName: [{ required: true, message: '用户名必输', trigger: 'blur' }],
        fullName: [{ required: true, message: '姓名必输', trigger: 'blur' }],
        password: [
          {
            trigger: 'blur',
            validator: (rules, value, callback) => {
              if (!this.temp.id && !value) {
                callback(new Error('密码必输'))
              } else if (this.temp.id > 0 && !value) {
                callback()
              } else {
                const reg =
                  /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*?]).{6,}$/
                if (!reg.test(value)) {
                  callback(
                    new Error('密码必须大于6位，并且包含特殊字符、大小写字母')
                  )
                } else {
                  callback()
                }
              }
            }
          }
        ],
        surePassword: [
          {
            trigger: 'blur',
            validator: (rules, value, callback) => {
              this.temp.password === value
                ? callback()
                : callback(new Error('密码不一致'))
            }
          }
        ],
        status: [{ required: true, message: '状态必选', trigger: 'blur' }]
      },
      // 角色列表，用于表单选择
      roles: []
    }
  },
  created() {
    // 获取用户列表
    this.getList()
    // 获取角色列表
    this.getRoleList()
  },
  methods: {
    // 获取用户列表
    getList() {
      this.listLoading = true
      getUserList(this.listQuery).then((res) => {
        console.log(111, res)
        this.list = res.users
        this.total = res.totalCount
        this.listLoading = false
      })
    },
    getRoleList() {
      this.listLoading = true
      getAllRoleList().then((res) => {
        // console.log(112, res)
        this.roles = res
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    resetName() {
      this.listQuery.name = ''
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        userName: '',
        fullName: '',
        remark: '',
        status: '正常'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate() // 清除表单验证状态
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // Object.assign 方法创建一个新的对象 作用：避免直接修改原数据，保持数据一致性，防止副作用
          const data = Object.assign({}, this.temp) // 复制 this.temp 对象到一个新的对象 data
          data.status = data.status === '正常' ? 1 : 0
          console.log('准备提交的用户数据:', data)
          addUser(data).then((response) => {
            console.log('新增用户成功，响应:', response)
            this.getList()
            this.dialogFormVisible = false
            // 发送通知消息
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          }).catch(error => {
            console.error('新增用户失败:', error)
          })
        } else {
          console.log('表单验证失败')
        }
      })
    },
    handleUpdate(row) {
      // 并将 row 对象的属性复制到新对象中 在新对象中初始化 roleNames 属性为一个空数组
      this.temp = Object.assign({ roleNames: [] }, row) // copy obj
      this.temp.status = this.temp.status === 1 ? '正常' : '禁用'
      this.temp.roleNames = this.temp.roles.map((x) => x.name)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.status = tempData.status === '正常' ? 1 : 0
          updateUser(tempData).then(() => {
            // 如果不写 findIndex，那么就无法确定 this.temp 在 this.list 中的位置，从而无法正确更新本地数据列表
            const index = this.list.findIndex((x) => x.id === this.temp.id)
            this.temp.status = this.temp.status === '正常' ? 1 : 0
            // 用于替换数组中指定索引位置的元素 确保本地数据列表 this.list 与更新后的数据保持一致
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUser(row.id).then((res) => {
            if (res && res.code !== 200) {
              this.$notify({
                message: '删除失败，错误原因：' + res.message,
                type: 'info'
              })
            } else {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.list.splice(index, 1)
            }
          })
        })
        .catch(() => {
          this.$notify({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
